package cn.foxtech.cloud.repository.service;

import cn.craccd.mongoHelper.utils.CriteriaAndWrapper;
import cn.foxtech.cloud.core.exception.ServiceException;
import cn.foxtech.cloud.repo.comp.haas.constants.ConstantRepoCompHaas;
import cn.foxtech.cloud.repo.comp.haas.entity.RepoCompHaasEntity;
import cn.foxtech.cloud.repo.comp.haas.entity.RepoCompHaasVersionEntity;
import cn.foxtech.cloud.repo.comp.haas.service.RepoCompHaasFileService;
import cn.foxtech.cloud.repo.comp.haas.service.RepoCompHaasService;
import cn.foxtech.cloud.repo.comp.haas.service.RepoCompHaasVersionService;
import cn.foxtech.common.utils.md5.MD5Utils;
import cn.foxtech.common.utils.method.MethodUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class RepoHaasUploadService {
    @Autowired
    private RepoCompHaasFileService fileService;

    @Autowired
    private RepoCompHaasService compService;

    @Autowired
    private RepoCompHaasVersionService versionService;


    public Map<String, Object> uploadComponent(String commitKey, Object file, Map<String, Object> param) throws IOException {
        if (!(file instanceof MultipartFile)) {
            throw new ServiceException("file 必须是 MultipartFile");
        }

        String userName = SecurityUtils.getUsername();
        if (MethodUtils.hasEmpty(userName)) {
            throw new ServiceException("获得登录用户信息失败!");
        }

        String hardManufacturer = (String) param.get(ConstantRepoCompHaas.field_hard_manufacturer);
        String hardDeviceType = (String) param.get(ConstantRepoCompHaas.field_hard_device_type);
        String softManufacturer = (String) param.get(ConstantRepoCompHaas.field_soft_manufacturer);
        String softDeviceType = (String) param.get(ConstantRepoCompHaas.field_soft_device_type);
        String description = (String) param.get(ConstantRepoCompHaas.field_description);

        // 检查：是否至少包含以下几个参数
        if (MethodUtils.hasEmpty(hardManufacturer, hardDeviceType, softManufacturer, softDeviceType)) {
            throw new ServiceException("body参数缺失: hardManufacturer, hardDeviceType, softManufacturer, softDeviceType");
        }


        CriteriaAndWrapper criteriaAndWrapper = this.compService.buildWrapper(param);
        RepoCompHaasEntity haasEntity = this.compService.queryEntity(criteriaAndWrapper);
        if (haasEntity == null) {
            throw new ServiceException("指定的实体不存在!");
        }


        if (!userName.equals("admin") && !haasEntity.getOwnerId().equals(userName)) {
            if (MethodUtils.hasEmpty(commitKey)) {
                throw new ServiceException("只有下列人员才可以提交：admin、owner和持有commitKey的人员：" + haasEntity.getGroupName());
            }

            // 验证提交密码
            if (!SecurityUtils.matchesPassword(commitKey, haasEntity.getCommitKey())) {
                throw new ServiceException("commitKey验证不通过！");
            }
        }

        MultipartFile multipartFile = (MultipartFile) file;


        File dir = new File("");
        String path = this.fileService.getHaasDirName(dir.getAbsolutePath(), haasEntity);


        // 保存成tmp文件
        String fileName = this.fileService.saveFile(multipartFile, path, System.currentTimeMillis());

        // 上传完成后，保存为实际扩展名文件
        this.fileService.rename(path, fileName + ".tmp", fileName);

        // 计算MD5验证码
        File md5File = new File(path + "/" + fileName);
        String md5Txt = MD5Utils.getMD5Txt(md5File);
        long fileSize = md5File.length();

        // 保存记录
        RepoCompHaasVersionEntity entity = new RepoCompHaasVersionEntity();
        entity.setHaasId(haasEntity.getId());
        entity.setAuthor(userName);
        entity.setFileName(fileName);
        entity.setOriginalFilename(multipartFile.getOriginalFilename());
        entity.setFileSize(fileSize);
        entity.setMd5(md5Txt);
        entity.setDescription(description);
        this.versionService.insertVersionEntity(entity);


        Map<String, Object> data = new HashMap<>();
        data.put("name", multipartFile.getOriginalFilename());
        data.put("url", fileName);

        return data;
    }
}
